<?php

namespace app\store\model;

use app\common\model\Order as OrderModel;
use app\store\model\OrderAddress as OrderAddressModel;
use app\store\model\User as UserModel;
use app\store\model\UserCoupon as UserCouponModel;
use app\store\service\order\Export as Exportservice;
use app\common\library\helper;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\DeliveryType as DeliveryTypeEnum;
use app\common\service\Message as MessageService;
use app\common\service\order\Refund as RefundService;
use app\common\service\wechat\wow\Order as WowService;
use app\common\service\goods\source\Factory as FactoryStock;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\Status as OrderStatusEnum;
use think\Db;
/**
 * 订单管理
 * Class Order
 * @package app\store\model
 */
class Order extends OrderModel
{

    /**
     * 储值卡充值订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function cardOrder($query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['orderplan', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where(['order.order_source'=>40])
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);

    }


    /**
     * 订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($dataType, $query = [])
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['goods.image', 'address', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($this->transferDataType($dataType))
           // ->where(['order.order_source'=>['IN',[10,20,30,40,50]]])
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->paginate(20, false, [
                'query' => \request()->request()
            ]);

    }





    /**
     * 订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getFinanceList($order_source,$query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        $where = ['order_source'=>$order_source,'pay_status'=>20,'order.is_delete'=>0];
        // 获取数据列表
        return $this->with(['goods.image', 'address', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($where)
            ->order(['order.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);

    }


    /**
     * 财务管理商品订单导出
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function goodsFinanceExport($order_source,$query = [])
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '客户列表';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getGoodsFinanceExport($order_source,$query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '客户id', '录入人', '录入人电话', '客户名称', '客户电话', '跟进人', '跟进人电话', '意向楼盘名称', '状态',
            '添加时间',
        ];


        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getGoodsFinanceExport($order_source,$query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }


    /**
     * 财务管理商品订单导出列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getGoodsFinanceExport($order_source,$query = [],$start, $limit,$count = false){
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        $where = ['order_source'=>$order_source,'pay_status'=>20,'order.is_delete'=>0];
        if($count==true){
            // 获取数据列表
            return $this->count();
        }
        // 获取数据列表
        $list =  $this->select();
        // 表格内容
        $dataArray = [];
        /*foreach ($list as $order) {
            $address = $order['address'];
            $goodsInfo = $this->filterGoodsInfo($order);

            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '商品信息' => $goodsInfo,
                '订单总额' => $this->filterValue($order['total_price']),
                '优惠券抵扣' => $this->filterValue($order['coupon_money']),
                '零钱抵扣' => $this->filterValue($order['balance_money']),
                '运费金额' => $this->filterValue($order['express_price']),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '买家留言' => $this->filterValue($order['buyer_remark']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];
        }*/

        return  $list;

    }




    /**
     * 财务管理消费订单导出
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function faceFinanceExport($order_source,$query = [])
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '消费订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getFaceFinanceExport($order_source,$query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '订单号', '订单总额', '优惠券抵扣', '零钱抵扣',  '实付款金额', '支付方式', '下单时间',
            '买家',  '付款状态', '付款时间', '微信支付交易号',
        ];


        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getFaceFinanceExport($order_source,$query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }


    /**
     * 财务管理商品订单导出列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getFaceFinanceExport($order_source,$query = [],$start, $limit,$count = false)
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        $where = ['order_source'=>$order_source,'pay_status'=>20,'order.is_delete'=>0];

        if($count==true){
            // 获取数据列表
            return $this->with(['goods.image', 'address', 'user'])
                ->alias('order')
                ->field('order.*')
                ->join('user', 'user.user_id = order.user_id')
                ->where($where)
                ->count();
        }
        // 获取数据列表
        $list =  $this->with(['goods.image', 'address', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($where)
            ->limit($start,$limit)
            ->order('order.pay_time desc')
            ->select();
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {

            $address = $order['address'];
            $goodsInfo = $this->filterGoodsInfo($order);

            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '订单总额' => $this->filterValue($order['total_price']),
                '优惠券抵扣' => $this->filterValue($order['coupon_money']),
                '零钱抵扣' => $this->filterValue($order['balance_money']),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];
        }



        return  $dataArray;

    }



    /**
     * 财务管理储值订单导出
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function cardFinanceExport($order_source,$query = [])
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '储值订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getCardFinanceExport($order_source,$query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '订单号', '订单总额',  '实付款金额', '支付方式', '下单时间',
            '买家',  '付款状态', '付款时间', '微信支付交易号',
        ];


        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getCardFinanceExport($order_source,$query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }


    /**
     * 财务管理储值订单导出列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getCardFinanceExport($order_source,$query = [],$start, $limit,$count = false)
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        $where = ['order_source'=>$order_source,'pay_status'=>20,'order.is_delete'=>0];

        if($count==true){
            // 获取数据列表
            return $this->with(['goods.image', 'address', 'user'])
                ->alias('order')
                ->field('order.*')
                ->join('user', 'user.user_id = order.user_id')
                ->where($where)
                ->count();
        }
        // 获取数据列表
        $list =  $this->with(['goods.image', 'address', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($where)
            ->limit($start,$limit)
            ->order('order.pay_time desc')
            ->select();
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {

            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '订单总额' => $this->filterValue($order['total_price']),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];
        }


        return  $dataArray;

    }






    /**
     * 订单列表(全部)
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getListAll($dataType, $query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['goods.image', 'address', 'user', 'extract', 'extract_shop'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($this->transferDataType($dataType))
            ->where(['order.order_source'=>['IN',[10,20,30]]])
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->select();
    }



    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList($dataType, $query)
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getExportList($dataType, $query,0, $limit,true);
        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
        '订单号', '商品信息', '订单总额', '优惠券抵扣', '零钱抵扣', '运费金额', '实付款金额', '支付方式', '下单时间',
        '买家', '买家留言', '付款状态', '付款时间', '微信支付交易号',
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');


        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getExportList($dataType, $query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }



    /**
     * 打印订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getExportList($dataType, $query = [],$start, $limit,$count = false)
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        if($count==true){
            // 获取数据列表
            return $this->with(['goods.image', 'address', 'user'])
                ->alias('order')
                ->field('order.*')
                ->join('user', 'user.user_id = order.user_id')
                ->where($this->transferDataType($dataType))
                ->where('order.is_delete', '=', 0)
                ->count();
        }
        // 获取数据列表
        $list =  $this->with(['goods.image', 'address', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($this->transferDataType($dataType))
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->limit($start,$limit)
            ->select();

        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            /* @var OrderAddressModel $address */
            $address = $order['address'];
            switch ($order['order_source']){
                case "10"://普通订单
                    $goodsInfo = $this->filterGoodsInfo($order);
                    break;
                case "20"://砍价订单
                    $goodsInfo= $this->filterGoodsInfo($order);
                    break;
                case "30"://秒杀订单
                    $goodsInfo= $this->filterGoodsInfo($order);
                    break;
                case "40"://储值卡订单
                    $goodsInfo= "储值卡订单";
                    break;
                case "50"://当面付
                    $goodsInfo= "当面付订单";
                    break;

            }

            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '商品信息' => $goodsInfo,
                '订单总额' => $this->filterValue($order['total_price']),
                '优惠券抵扣' => $this->filterValue($order['coupon_money']),
                '零钱抵扣' => $this->filterValue($order['balance_money']),
                '运费金额' => $this->filterValue($order['express_price']),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '买家留言' => $this->filterValue($order['buyer_remark']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];
        }

        return  $dataArray;

    }



    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private function filterGoodsInfo($order)
    {

        $content = '';
        foreach ($order['goods'] as $key => $goods) {
            $content .= ($key + 1) . ".商品名称：{$goods['goods_name']}\n";
            !empty($goods['goods_attr']) && $content .= "　商品规格：{$goods['goods_attr']}\n";
            $content .= "　购买数量：{$goods['total_num']}\n";
            $content .= "　商品总价：{$goods['total_price']}元\n\n";
        }
        return $content;
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }


    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {

        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }

    /**
     * 储值卡订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportCardList($query)
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '储值卡订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->gettCardListAll($query,0, $limit,true);
        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }
        $xlsTitle = [
            '订单编号', '储值卡', '订单金额', '赠送积分', '下单人', '交易状态', '下单时间'
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');



        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->gettCardListAll($query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件


    }


    /**
     * 储值卡订单导出
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function gettCardListAll($query = [],$start, $limit,$count = false)
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        if($count==true){
            // 获取数据列表
            return $this->with(['orderplan', 'user'])
                ->alias('order')
                ->field('order.*')
                ->join('user', 'user.user_id = order.user_id')
                ->where(['order.order_source'=>40])
                ->where('order.is_delete', '=', 0)
                ->order(['order.create_time' => 'desc'])
                ->count();
        }

        // 获取数据列表
        $list =  $this->with(['orderplan', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where(['order.order_source'=>40])
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->limit($start,$limit)
            ->select();

        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            $dataArray[] = [
                '订单编号' => $this->filterValue($order['order_no']),
                '储值卡' => $this->filterValue($order['orderplan']['card_title']),
                '订单金额' => $this->filterValue($order['pay_price']),
                '赠送积分' => $this->filterValue($order['orderplan']['reward_percent']),
                '下单人' => $this->filterValue($order['user']['nickName']),
                '交易状态' => $this->filterValue($order['pay_status']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
            ];
        }

        return $dataArray;
    }


    /**
     * 批量发货模板
     */
    public function deliveryTpl()
    {
        return (new Exportservice)->deliveryTpl();
    }

    /**
     * 设置检索查询条件
     * @param $query
     */
    private function setWhere($query)
    {
        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('order_no|user.nickName', 'like', '%' . trim($query['search']) . '%');
        }

        if (isset($query['start_time']) && !empty($query['start_time'])) {
            $this->where('order.create_time', '>=', strtotime($query['start_time']));
        }
        if (isset($query['end_time']) && !empty($query['end_time'])) {
            $this->where('order.create_time', '<', strtotime($query['end_time']) + 86400);
        }
        if (isset($query['delivery_type']) && !empty($query['delivery_type'])) {
            $query['delivery_type'] > -1 && $this->where('delivery_type', '=', $query['delivery_type']);
        }
        if (isset($query['order_source']) && !empty($query['order_source'])) {
            $query['order_source'] > -1 && $this->where('order_source', '=', $query['order_source']);
        }
        if (isset($query['extract_shop_id']) && !empty($query['extract_shop_id'])) {
            $query['extract_shop_id'] > -1 && $this->where('extract_shop_id', '=', $query['extract_shop_id']);
        }
        // 用户id
        if (isset($query['user_id']) && $query['user_id'] > 0) {
            $this->where('order.user_id', '=', (int)$query['user_id']);
        }
        // 订单状态
        if (isset($query['pay_status']) && $query['pay_status'] > 0) {
            $this->where('order.pay_status', '=', (int)$query['pay_status']);
        }
        // 订单状态
        if (isset($query['pay_type']) && $query['pay_type'] > 0) {
            $this->where('order.pay_type', '=', (int)$query['pay_type']);
        }
    }

    /**
     * 转义数据类型条件
     * @param $dataType
     * @return array
     */
    private function transferDataType($dataType)
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case 'delivery':
                $filter = [
                    'pay_status' => 20,
                    'delivery_status' => 10,
                    'order_status' => ['in', [10, 21]]
                ];
                break;
            case 'receipt':
                $filter = [
                    'pay_status' => 20,
                    'delivery_status' => 20,
                    'receipt_status' => 10
                ];
                break;
            case 'pay':
                $filter = ['pay_status' => 10, 'order_status' => 10];
                break;
            case 'complete':
                $filter = ['order_status' => 30];
                break;
            case 'cancel':
                $filter = ['order_status' => 20];
                break;
            case 'all':
                $filter = [];
                break;
        }
        return $filter;
    }

    /**
     * 确认发货(单独订单)
     * @param $data
     * @return array|bool|false
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function delivery($data)
    {
        // 转义为订单列表
        $orderList = [$this];
        // 验证订单是否满足发货条件
        if (!$this->verifyDelivery($orderList)) {
            return false;
        }
        // 整理更新的数据
        $updateList = [[
            'order_id' => $this['order_id'],
            'express_id' => $data['express_id'],
            'express_no' => $data['express_no']
        ]];
        // 更新订单发货状态
        if ($status = $this->updateToDelivery($updateList)) {
            // 获取已发货的订单
            $completed = self::detail($this['order_id'], ['user', 'address', 'goods', 'express']);
            // 发送消息通知
            $this->sendDeliveryMessage([$completed]);
            // 同步好物圈订单
            (new WowService($this['wxapp_id']))->update([$completed]);
        }
        return $status;
    }

    /**
     * 批量发货
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function batchDelivery($data)
    {
        // 获取csv文件中的数据
        if (!$csvData = $this->getCsvData()) {
            return false;
        }
        // 整理订单id集
        $orderNos = helper::getArrayColumn($csvData, 0);
        // 获取订单列表数据
        $orderList = helper::arrayColumn2Key($this->getListByOrderNos($orderNos), 'order_no');
        // 验证订单是否存在
        $tempArr = array_values(array_diff($orderNos, array_keys($orderList)));
        if (!empty($tempArr)) {
            $this->error = "订单号[{$tempArr[0]}] 不存在!";
            return false;
        }
        // 整理物流单号
        $updateList = [];
        foreach ($csvData as $item) {
            $updateList[] = [
                'order_id' => $orderList[$item[0]]['order_id'],
                'express_id' => $data['express_id'],
                'express_no' => $item[1],
            ];
        }
        // 验证订单是否满足发货条件
        if (!$this->verifyDelivery($orderList)) {
            return false;
        }
        // 更新订单发货状态(批量)
        if ($status = $this->updateToDelivery($updateList)) {
            // 获取已发货的订单
            $completed = $this->getListByOrderNos($orderNos, ['user', 'address', 'goods', 'express']);
            // 发送消息通知
            $this->sendDeliveryMessage($completed);
            //  同步好物圈订单
            (new WowService(self::$wxapp_id))->update($completed);
        }
        return $status;
    }

    /**
     * 确认发货后发送消息通知
     * @param $orderList
     * @return bool
     */
    private function sendDeliveryMessage($orderList)
    {
        // 发送消息通知
        foreach ($orderList as $item) {
            MessageService::send('order.delivery', [
                'order' => $item,
                'order_type' => OrderTypeEnum::MASTER,
            ]);
        }
        return true;
    }

    /**
     * 更新订单发货状态(批量)
     * @param $orderList
     * @return array|false
     * @throws \Exception
     */
    private function updateToDelivery($orderList)
    {
        $data = [];
        foreach ($orderList as $item) {
            $data[] = [
                'order_id' => $item['order_id'],
                'express_no' => $item['express_no'],
                'express_id' => $item['express_id'],
                'delivery_status' => 20,
                'delivery_time' => time(),
            ];
        }
        return $this->isUpdate()->saveAll($data);
    }

    /**
     * 验证订单是否满足发货条件
     * @param $orderList
     * @return bool
     */
    private function verifyDelivery($orderList)
    {
        foreach ($orderList as $order) {
            if (
                $order['pay_status']['value'] != 20
                || $order['delivery_type']['value'] != DeliveryTypeEnum::EXPRESS
                || $order['delivery_status']['value'] != 10
            ) {
                $this->error = "订单号[{$order['order_no']}] 不满足发货条件!";
                return false;
            }
        }
        return true;
    }

    /**
     * 获取csv文件中的数据
     * @return array|bool
     */
    private function getCsvData()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = \request()->file('iFile');
        if (empty($file)) {
            $this->error = '请上传发货模板';
            return false;
        }
        // 设置区域信息
        setlocale(LC_ALL, 'zh_CN');
        // 打开上传的文件
        $csvFile = fopen($file->getInfo()['tmp_name'], 'r');
        // 忽略第一行(csv标题)
        fgetcsv($csvFile);
        // 遍历并记录订单信息
        $orderList = [];
        while ($item = fgetcsv($csvFile)) {
            if (!isset($item[0]) || empty($item[0]) || !isset($item[1]) || empty($item[1])) {
                $this->error = '模板文件数据不合法';
                return false;
            }
            $orderList[] = $item;
        }
        if (empty($orderList)) {
            $this->error = '模板文件中没有订单数据';
            return false;
        }
        return $orderList;
    }

    /**
     * 修改订单价格
     * @param $data
     * @return bool
     */
    public function updatePrice($data)
    {
        if ($this['pay_status']['value'] != 10) {
            $this->error = '该订单不合法';
            return false;
        }
        // 实际付款金额
        $payPrice = bcadd($data['update_price'], $data['update_express_price'], 2);
        if ($payPrice <= 0) {
            $this->error = '订单实付款价格不能为0.00元';
            return false;
        }
        return $this->save([
                'order_no' => $this->orderNo(), // 修改订单号, 否则微信支付提示重复
                'order_price' => $data['update_price'],
                'pay_price' => $payPrice,
                'update_price' => helper::bcsub($data['update_price'], helper::bcsub($this['total_price'], $this['coupon_money'])),
                'express_price' => $data['update_express_price']
            ]) !== false;
    }


    /**
     * 审核：用户取消订单
     * @param $data
     * @return bool|mixed
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function newconfirmcancel($data)
    {

        // 订单取消事件
        $status = $this->transaction(function () use ($data) {
            if ($data['is_cancel'] == true) {

                // 回退商品库存
                FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], true);
                // 回退用户优惠券
                $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
                // 回退用户积分
                $User = UserModel::detail($this['user_id']);
                $describe = "订单取消：{$this['order_no']}";
                $this['points_num'] > 0 && $User->setIncPoints($this['points_num'], $describe);
                // 回退用户零钱
                $this['balance_num'] > 0 && $User->setIncBalance($this['balance_num'], $describe,40);
            }
            // 更新订单状态
            return $this->save(['order_status' => $data['is_cancel'] ? 20 : 10]);
        });
        if ($status == true) {
            // 同步好物圈订单
            //(new WowService(self::$wxapp_id))->update([$this]);
        }
        return $status;
    }


    /**
     * 审核：用户取消订单
     * @param $data
     * @return bool|mixed
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function confirmCancel($data)
    {
        // 判断订单是否有效
        if ($this['pay_status']['value'] != 20) {
            $this->error = '该订单不合法';
            return false;
        }

        // 订单取消事件
        $status = $this->transaction(function () use ($data) {
            if ($data['is_cancel'] == true) {
                //根据订单支付方式进行退款操作
                //余额支付
                if($this['pay_type']['value']==10){
                    //储蓄余额
                    if($this['pay_way']==10){
                        if($this['delivery_status']['value']==10){
                            //未发货
                            //更新储蓄余额流水
                            $userMoneyData=[
                                'user_id'=>$this['user_id'],
                                'scene'=>20,
                                'money'=>$this['total_price'],
                                'describe'=>'用户取消订单',
                                'remark'=>'用户取消订单',
                                'order_no'=>$this['order_no'],
                                'wxapp_id'=>$this['wxapp_id'],
                                'create_time'=>time()
                            ];
                            Db::name('user_money_log')->insert($userMoneyData);
                            //更新储蓄总金额
                            Db::name('user')->where(['user_id'=>$this['user_id']])->setInc('money',$this['total_price']);
                            // 更新订单状态
                            return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' =>20]);
                        }
                    }else{
                        if($this['delivery_status']['value']==10){
                            //未发货
                            //收益余额
                            //更新收益余额流水
                            $delerMoneyData=[
                                'user_id'=>$this['user_id'],
                                'flow_type'=>80,
                                'money'=>$this['total_price'],
                                'describe'=>'用户取消订单',
                                'wxapp_id'=>$this['wxapp_id'],
                                'create_time'=>time(),
                                'update_time'=>0
                            ];
                            Db::name('dealer_capital')->insert($delerMoneyData);
                            //更新收益总金额
                            Db::name('dealer_user')->where(['user_id'=>$this['user_id']])->setInc('money',$this['total_price']);
                            // 更新订单状态
                            return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' =>20]);
                        }
                    }
                    // 回退商品库存
                    FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], true);
                    // 回退用户优惠券
                    $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
                }else{
                    // 执行退款操作
                    (new RefundService)->execute($this);
                    // 回退商品库存
                    FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], true);
                    // 回退用户优惠券
                    $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
                    // 回退用户积分
                    $User = UserModel::detail($this['user_id']);
                    $describe = "订单取消：{$this['order_no']}";
                    $this['points_num'] > 0 && $User->setIncPoints($this['points_num'], $describe);
                    // 回退用户零钱
                    $this['balance_num'] > 0 && $User->setIncBalance($this['balance_num'], $describe,40);
                }



            }
            // 更新订单状态
            return $this->isUpdate(true)->save(['order_status' => $data['is_cancel'] ? 20 : 10]);
        });
        if ($status == true) {
            // 同步好物圈订单
            (new WowService(self::$wxapp_id))->update([$this]);
        }
        return $status;
    }

    /**
     * 获取已付款订单总数 (可指定某天)
     * @param null $startDate
     * @param null $endDate
     * @return int|string
     * @throws \think\Exception
     */
    public function getPayOrderTotal($startDate = null, $endDate = null)
    {
        $filter = [
            'pay_status' => PayStatusEnum::SUCCESS,
            'order_status' => ['<>', OrderStatusEnum::CANCELLED],
        ];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter['pay_time'] = [
                ['>=', strtotime($startDate)],
                ['<', strtotime($endDate) + 86400],
            ];
        }

        $giftsFilter = [
            'pay_status' => PayStatusEnum::SUCCESS,
            'wxapp_id' => self::$wxapp_id,
        ];
        if (!is_null($startDate) && !is_null($endDate)) {
            $giftsFilter['pay_time'] = [
                ['>=', strtotime($startDate)],
                ['<', strtotime($endDate) + 86400],
            ];
        }

        //普通订单
        $order = $this->getOrderTotal($filter);
        //爆品订单
        $giftsOrder = db('gifts_order')->where($giftsFilter)->count();

        return  $order+$giftsOrder;
    }
    /**
     * 获取余额订单总数 (可指定某天)
     */
    public function getOrderYueTotal($startDate = null, $endDate = null){
        $filter = [
            'pay_status' => PayStatusEnum::SUCCESS,
            'order_status' => ['<>', OrderStatusEnum::CANCELLED],
            'pay_type'=>10
        ];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter['pay_time'] = [
                ['>=', strtotime($startDate)],
                ['<', strtotime($endDate) + 86400],
            ];
        }
        return $this->getOrderTotal($filter);
    }
    /**
     * 获取某天的余额支付总金额
     */
    public function getOrderYueTotalPrice($startDate = null, $endDate = null){
        if (!is_null($startDate) && !is_null($endDate)) {
            $this->where('pay_time', '>=', strtotime($startDate))
                ->where('pay_time', '<', strtotime($endDate) + 86400);
        }
        return $this->where('pay_status', '=', 20)
            ->where('order_status', '<>', 20)
            ->where('is_delete', '=', 0)
            ->where('pay_type', '=', 10)
            ->sum('pay_price');
    }
    /**
     * 获取订单总数量
     * @param array $filter
     * @return int|string
     * @throws \think\Exception
     */
    private function getOrderTotal($filter = [])
    {
        return $this->where($filter)
            ->where('is_delete', '=', 0)
            ->count();
    }

    /**
     * 获取某天的总销售额
     * @param null $startDate
     * @param null $endDate
     * @return float|int
     */
    public function getOrderTotalPrice($startDate = null, $endDate = null)
    {
        if (!is_null($startDate) && !is_null($endDate)) {
            $this->where('pay_time', '>=', strtotime($startDate))
                ->where('pay_time', '<', strtotime($endDate) + 86400);
        }

        $giftsFilter = [
            'pay_status' => 20,
            'wxapp_id' => self::$wxapp_id,
        ];
        if (!is_null($startDate) && !is_null($endDate)) {
            $giftsFilter['pay_time'] = [
                ['>=', strtotime($startDate)],
                ['<', strtotime($endDate) + 86400],
            ];
        }

        //普通订单
        $commOrder = $this->where('pay_status', '=', 20)
            ->where('order_status', '<>', 20)
            ->where('is_delete', '=', 0)
            ->sum('pay_price');

        //爆品订单
        $giftsOrder = db('gifts_order')->where($giftsFilter)->sum('pay_price');

        return bcadd($commOrder,$giftsOrder,2);

    }

    /**
     * 获取某天的下单用户数
     * @param $day
     * @return float|int
     */
    public function getPayOrderUserTotal($day)
    {
        $startTime = strtotime($day);
        //普通订单
        $commUserIds = $this->distinct(true)
            ->where('pay_time', '>=', $startTime)
            ->where('pay_time', '<', $startTime + 86400)
            ->where('pay_status', '=', 20)
            ->where('is_delete', '=', 0)
            ->column('user_id');

        //爆品
        $giftsUserIds = db('gifts_order')
            ->distinct(true)
            ->where('pay_time', '>=', $startTime)
            ->where('pay_time', '<', $startTime + 86400)
            ->where('pay_status', '=', 20)
            ->where('wxapp_id', '=', self::$wxapp_id)
            ->where('is_delete', '=', 0)
            ->column('user_id');
        $mergeUserIds = array_merge($commUserIds,$giftsUserIds);

        return count(array_unique($mergeUserIds));

    }


    /**
     * 获取订单总数量
     * @param array $order_id
     * @return int|string
     * @throws \think\Exception
     */
    public function orderDel()
    {
        return $this->delete() !== false;
    }
}
